package com.jml.demo.order;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.MessageQueueSelector;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;
import org.apache.rocketmq.remoting.common.RemotingHelper;

import java.util.List;

/**
 * 顺序消息
 */
public class OrderedProducer {
    public static void main(String[] args) throws Exception {
        DefaultMQProducer producer = new DefaultMQProducer("example_group_name");
        producer.setNamesrvAddr("172.26.3.145:9876");
        //二组订单为例，每组订单发送5条数据，i是顺序号，j是订单号，
        producer.start();
        for (int i = 0; i < 5; i++) {
            for(int j=100;j<102;j++){
                int orderId = j;
                //构建message对象
                Message msg = new Message("TopicOrder",
                        ("orderId:"+orderId+",num:" + i).getBytes(RemotingHelper.DEFAULT_CHARSET));
                //生产者:单线程发送
                //指定topic ，选择topic对应的队列
                //MessageQueueSelector 实现Queue选择，达到相同的订单id获取相同的队列
                //第三个参数就是一个标识，我们根据这个标识来选择队列
                SendResult sendResult = producer.send(msg,
                        new MessageQueueSelector() {
                            @Override
                            //给消息指定队列
                            //mqs:当前topic包含多少个队列，返回值 当前的消息对应的消息队列
                            public MessageQueue select(List<MessageQueue> mqs, Message msg, Object arg) {
                                //这个就是外面的第二个参数
                                Integer id = (Integer) arg; //订单ID  orderId
                                int index = id % mqs.size(); //100%3 ,101%3
                                //相同的订单ID，会得到相同的队列
                                MessageQueue queue = mqs.get(index);
                                System.out.println("orderId:"+id+",index:"+index+",queue:"+queue);
                                return queue;
                            }
                        }, orderId);
            }
        }
        producer.shutdown();
    }
}
